package loginDao

import _ "github.com/go-sql-driver/mysql"
import (
	"database/sql"
	"fmt"
	"homework/work2/task/domain"
	"strings"
)

//数据库配置
const (
	userName = "root"
	password = "******!"
	ip       = "127.0.0.1"
	port     = "3306"
	dbName   = "userDB"
)

//Db数据库连接池
var DB *sql.DB

//初始化数据库连接
func init() {
	//构建连接
	path := strings.Join([]string{userName, ":", password, "@tcp(", ip, ":", port, ")/", dbName, "?charset=utf8"}, "")

	//打开数据库
	DB, _ = sql.Open("mysql", path)
	//设置数据库最大连接数
	DB.SetConnMaxLifetime(100)
	//设置上数据库最大闲置连接数
	DB.SetMaxIdleConns(10)

	if err := DB.Ping(); err != nil {
		fmt.Println("open database fail")
		return
	}
	fmt.Println("connnect success")
}

/*
 *处理方式一
 *  在Dao层处理sql.ErrNoRows
 *  查询结果返回nil，调用者判断返回结果是否为nil
 *  根据返回结果处理业务逻辑
 */
func GetUserById(id string) (*domain.User, error) {
	user := new(domain.User)
	err := DB.QueryRow("SELECT id, code, `name` FROM user_test WHERE id = ? ", id).Scan(&user.Id, &user.UserCode, &user.Name)
	if err == sql.ErrNoRows {
		return nil, nil
	}

	return user, err
}

/**
 *处理方式二
 *  在Dao层Wrap error
 *  调用者根据预定义错误值来处理业务逻辑
 */
type QueryError struct {
	msg string
	err error
}

func (e *QueryError) Error() string {
	return e.msg
}

func (e *QueryError) Unwrap() error {
	return e.err
}

func GetUserById2(id string) (*domain.User, error) {
	user := new(domain.User)
	err := DB.QueryRow("SELECT id, code, `name` FROM user_test WHERE id = ? ", id).Scan(&user.Id, &user.UserCode, &user.Name)
	if err == sql.ErrNoRows {
		return user, &QueryError{msg: "用户不存在", err: err}
	}

	return user, err
}


